/*
 * ImportFilesDialog.java
 *
 *  created: 7.10.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.k3bg.gui;

import static cz.mp.k3bg.Constants.*;
import cz.mp.k3bg.Images;
import static cz.mp.k3bg.Images.CANCEL;
import static cz.mp.k3bg.Images.OK;
import static cz.mp.k3bg.TextSource.getLocText;
import cz.mp.k3bg.core.HtmlFilesImporter;
import cz.mp.k3bg.core.SingleFileImporter;
import cz.mp.k3bg.gui.component.FileChooserField;
import cz.mp.k3bg.gui.component.FilesList;
import cz.mp.k3bg.gui.component.IndeterminateProgressDialog;
import cz.mp.k3bg.log.LoggerManager;
import cz.mp.util.GuiUtils;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import net.miginfocom.swing.MigLayout;

/**
 * Dialog pro import souborů potřebných pro vytvoření knihy do pracovního
 * adresáře; importované soubory jsou přizpůsobeny.
 * Import se provádí na pozadí.
 * 
 * @author Martin Pokorný
 * @version 0.1
 * @see HtmlFilesImporter
 */
public class ImportFilesDialog extends JDialog {

    private static final boolean DEBUG = false;
    private static final Logger logger =
            LoggerManager.getLogger(ImportFilesDialog.class, DEBUG);    

    private static ImportFilesDialog instance = null;  
    
    private JLabel htmlFilesLabel = new JLabel(getLocText("gui.bookfiles.import.html"));
    private FilesList htmlFiles = new FilesList();

    private JLabel htmlNoteLabel = new JLabel(getLocText("gui.bookfiles.import.html_note"));
    
    private JLabel coverFileLabel = new JLabel(getLocText("gui.bookfiles.import.cover"));
    private FileChooserField coverFileField = new FileChooserField();
    private JLabel coverNoteLabel = new JLabel(getLocText("gui.bookfiles.import.cover_note"));
    
    private JButton importButton = new JButton(
            getLocText("gui.bookfiles.import.import"), Images.getImage(OK));
    private JButton cancelButton = new JButton(
            getLocText("gui.cancel"), Images.getImage(CANCEL));
    
    private String destDir;
    
    // -----
    
    /** */
    public ImportFilesDialog() {
        super(MainFrame.getInstance(), ModalityType.APPLICATION_MODAL);
        initComponents();
        initLayout();
        initHandlers();
        initDialog();
    }

    /**
     * 
     * @return 
     */
    private static ImportFilesDialog getInstance() {
        if (instance == null) {
            instance = new ImportFilesDialog();            
        }
        return instance;
    }    

    /**
     *
     * @param destDir  tam se budou kopírovat výsledné soubory
     */
    public static void showDialog(String destDir) {
        getInstance();
        
        instance.destDir = destDir;
        instance.htmlFiles.clear();
        instance.coverFileField.clear();
        
        instance.setVisible(true);
    }

    /**
     *
     */
    private void initDialog() {
        setTitle(getLocText("gui.bookfiles.import.title"));

        pack();
        setMinimumSize(new Dimension(400, getHeight()));
        setSize(MainFrame.getInstance().getWidth() - 60, getHeight() + 30);

        setLocationRelativeTo(MainFrame.getInstance());

        GuiUtils.addHideActionWithEscapeKey(this);
    }

    /**
     * 
     */
    private void initComponents() {
        htmlNoteLabel.setPreferredSize(new Dimension(1, 1));
        coverNoteLabel.setPreferredSize(new Dimension(1, 1));
        
        htmlFilesLabel.setLabelFor(htmlFiles);
        coverFileLabel.setLabelFor(coverFileField);

        htmlFiles.setUpDownArrowButtonsVisible(false);

        htmlFiles.setFilter(HTML_FILEFILTER);        
        coverFileField.setFilter(COVER_FILEFILTER);        

        htmlFiles.clear();
        coverFileField.clear();

        getRootPane().setDefaultButton(importButton);
    }
    
    /**
     * 
     */
    private void initLayout() {
        this.setLayout(new MigLayout("",
                "unrel[label]rel[fill,grow]unrel",
                "unrel[]rel[]unrel[]rel[]para[grow,bottom,nogrid]unrel"));
        
        this.add(htmlFilesLabel, "top");
        this.add(htmlFiles, "wrap");
        
        this.add(htmlNoteLabel, "skip, wrap");
        
        this.add(coverFileLabel);
        this.add(coverFileField, "wrap");
        this.add(coverNoteLabel, "skip, wrap");
        
        this.add(importButton, "tag ok, sg");
        this.add(cancelButton, "tag cancel, sg");
    }
    
    /**
     * 
     */
    private void initHandlers() {
        importButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                importtOnBackground();
                setVisible(false);
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                setVisible(false);
            }
        });         
    }

    /**
     * 
     */
    private void importtOnBackground() {
        new ImportTask().execute();
    }

    /**
     *
     * @throws IOException
     */
    private void importt() throws IOException {
        if (! htmlFiles.getFiles().isEmpty()) {
            HtmlFilesImporter htmlImporter =
                    new HtmlFilesImporter(destDir);
            htmlImporter.addFiles(
                    htmlFiles.getFiles());
            htmlImporter.importt();
        }

        if (coverFileField.isSelectedFile()) {
            SingleFileImporter coverImporter =
                    new SingleFileImporter(destDir);
            coverImporter.setSrcFilePath(
                    coverFileField.getSelectedFilePath());
            coverImporter.importt();
        }        
    }
    

    // -------------------------------------------------------------------------

    /**
     * Provede import souborů na pozadí.
     */
    private class ImportTask extends SwingWorker<Boolean, Integer> {

        private IndeterminateProgressDialog progressDialog;

        /** */
        private void showProgressDialog() {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    progressDialog = new IndeterminateProgressDialog(
                            MainFrame.getInstance());
                    progressDialog.showDialog();
                }
            });
        }

        /** */
        private void hideProgressDialog() {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    progressDialog.closeDialog();
                }
            });
        }

        @Override
        protected Boolean doInBackground() throws Exception {
            try {
                showProgressDialog();

                importt();

                if (DEBUG) {
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException ex) {
                    }
                    throw new IOException("TEST!!!");
                }
                
            } catch (Exception ex) {
                if (DEBUG) {  ex.printStackTrace();  }
                logger.warning(ex.toString());

                hideProgressDialog();
                Dialogs.showErrorDialog(ex);

                return Boolean.FALSE;
            }

            return Boolean.TRUE;
        }

        @Override
        protected void done() {
            hideProgressDialog();
        }

    }   // ImportTask

}   // ImportFilesDialog.java

